<?php

require_once __DIR__ . '/vendor/autoload.php';

use App\Core\Router;
use App\Core\Database;
use App\Core\Response;
use Dotenv\Dotenv;

// 加载环境变量
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

// 错误处理
$debug = isset($_ENV['APP_DEBUG']) ? $_ENV['APP_DEBUG'] : 'true';
error_reporting($debug === 'true' ? E_ALL : 0);
ini_set('display_errors', $debug === 'true' ? '1' : '0');

// CORS处理
$corsOrigin = isset($_ENV['CORS_ORIGIN']) ? $_ENV['CORS_ORIGIN'] : '*';
header('Access-Control-Allow-Origin: ' . $corsOrigin);
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

header('Content-Type: application/json; charset=utf-8');

try {
    // 初始化数据库连接
    Database::getInstance();
    
    // 初始化路由
    $router = new Router();
    require_once __DIR__ . '/routes/api.php';
    
    // 处理请求
    $router->dispatch();
    
} catch (Exception $e) {
    Response::error($e->getMessage(), 500);
}

